//
//  MJModifyPersonalInfoController.m
//  MJ
//
//  Created by qiaoBu on 2017/12/8.
//  Copyright © 2017年 lina. All rights reserved.
//

#import "MJModifyPersonalInfoController.h"
#import "MJModifyInfoTableViewCell.h"
#import "MJModifyNicknameController.h"
#import "MJChooseImageView.h"
//相册
#import <AssetsLibrary/AssetsLibrary.h>
//相机
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import "MJChangeHeaderImageTool.h"
#import "MJMyInfoViewModel.h"
#import "MJLoginViewController.h"

@interface MJModifyPersonalInfoController ()<UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) UITableView *modifyTableView;
@property (nonatomic, strong) NSArray *titlesArr;
@property (nonatomic, strong) MJChooseImageView *chooseImageView;
@property (nonatomic, copy) NSString *username;
@property (nonatomic, copy) NSString *spic;

@end

@implementation MJModifyPersonalInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navgationBar.titleLabel.text = @"个人信息";
    self.view.backgroundColor = RGBColor(242,242,242);
    [self commonInit];
}
- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [self refreshUI];
}

- (void)refreshUI{
    
    self.spic = [[NSUserDefaults standardUserDefaults] objectForKey:MJ_HeaderImage];
    
    self.username = [[NSUserDefaults standardUserDefaults] objectForKey:MJ_Name];
    
    [self.modifyTableView reloadData];
}

- (void)requestMyInfo{
    
    [MJMyInfoViewModel requestMyInfoSuccess:^(NSString *stateCode, MJMeInfoModel *infoModel, NSString *messageState) {
        
        if ([stateCode isEqualToString:@"001"])
        {
            self.username = [NSString stringWithFormat:@"%@",infoModel.alias];
            self.spic = [NSString stringWithFormat:@"%@",infoModel.spic];
            [self.modifyTableView reloadData];
        }
        else if ([stateCode isEqualToString:@"203"])
        {
            MJLoginViewController *loginController = [[MJLoginViewController alloc] init];
            [self.navigationController pushViewController:loginController animated:YES];
        }
        else
        {
            [TJMBProgressView showTingJianText:messageState];
        }
        
    } failure:^(NSError *error) {
        
        [TJMBProgressView showTingJianText:networkError];
        
    } netWorkState:^(BOOL netWorkState) {
        
    }];
}
- (void)commonInit{
    
    _titlesArr = @[@"头像",@"昵称"];

    [self.view addSubview:self.modifyTableView];
    self.modifyTableView.delegate = self;
    self.modifyTableView.dataSource = self;
    self.modifyTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [[UIApplication sharedApplication].keyWindow addSubview:self.chooseImageView];
    self.chooseImageView.hidden = YES;
    
    @weakify(self)
    [self.chooseImageView setChooseImageBlock:^(NSInteger buttonTag) {
    @strongify(self)
        
        ALAuthorizationStatus  author = [ALAssetsLibrary authorizationStatus];
        if(author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied)
        {
            UIAlertView *authorAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"需要访问你的相册，请在设置-->隐私-->相册，中开启本应用的相册访问权限！！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [authorAlertView show];
        }
        else
        {
            
            if (buttonTag == 10)
            {
                if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
                {
                    //相机
                    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
                    imagePickerController.delegate = self;
                    imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                    [self presentViewController:imagePickerController animated:YES completion:0];
                }
            }
            else
            {
                if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary])
                {
                   //相册集
                    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
                    imagePickerController.delegate = self;
                    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    [self presentViewController:imagePickerController animated:YES completion:0];
                }
            }
        }
        
    }];
}
#pragma mark - imagePicker代理
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    [self dismissViewControllerAnimated:YES completion:0];
    
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    if (image)
    {
        [self submitImageToServiceWithImage:image];
    }
    [picker dismissViewControllerAnimated:YES completion:^{}];
}

- (void)submitImageToServiceWithImage:(UIImage *)image{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    // 设置时间格式
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
    
    NSMutableDictionary *picDict = [NSMutableDictionary dictionary];
    [picDict setObject:@"1" forKey:@"type"];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.7);
    
    NSString *totalPath = [MJChangeHeaderImageTool saveImageData:imageData toDocumentsWithFileName:fileName];
    NSLog(@"totalPath ---------- %@",totalPath);
    
    [TJMBProgressView showTingJianTextNeverDismiss:@"上传中" Frame:self.view.bounds toView:self.view];
    [MJMyInfoViewModel requestUploadHeadImageWithImagePath:totalPath andNSMutableDictionary:picDict Success:^(NSString *stateCode, NSString *imageUrl, NSString *messageState) {

          [TJMBProgressView hideHUDForView:self.view];
        if ([stateCode isEqualToString:@"001"])
        {
            self.spic = imageUrl;
            [[NSUserDefaults standardUserDefaults] setObject:self.spic forKey:MJ_HeaderImage];
            [self.modifyTableView reloadData];
        }
        else
        {
            [TJMBProgressView showTingJianText:messageState];
        }
        [MJChangeHeaderImageTool deleteImageResourceWithPath:totalPath];
    } failure:^(NSError *error) {

        [TJMBProgressView hideHUDForView:self.view];
        [TJMBProgressView showTingJianText:networkError];

    } netWorkState:^(BOOL netWorkState) {

    }];
}

- (void)requestUploadImage{
    
    NSMutableDictionary *picDict = [NSMutableDictionary dictionary];
    [picDict setObject:[NSString stringWithFormat:@"%@",self.spic] forKey:@"spic"];
    [MJMyInfoViewModel requestChangeInfoWithDictionary:picDict Success:^(NSString *stateCode, NSString *messageState) {
        
        [TJMBProgressView hideHUDForView:self.view];
        
        if ([stateCode isEqualToString:@"001"])
        {
            
            //刷新数据
            [self.modifyTableView reloadData];
        }
        else
        {
            [TJMBProgressView showTingJianText:messageState];
        }
    } failure:^(NSError *error) {
        
        [TJMBProgressView hideHUDForView:self.view];
        [TJMBProgressView showTingJianText:networkError];
        
    } netWorkState:^(BOOL netWorkState) {
        
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellID = @"cellID";
    MJModifyInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell)
    {
        cell = [[MJModifyInfoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    [cell refreshCellWithTitle:self.titlesArr[indexPath.row] image:self.spic name:self.username andIndexPath:indexPath];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0)
    {
        self.chooseImageView.hidden = NO;
    }
    else
    {
        MJModifyNicknameController *nickNameController = [[MJModifyNicknameController alloc] init];
        [self.navigationController pushViewController:nickNameController animated:YES];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 135/2.0f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return [UIView new];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return [UIView new];
}
- (UITableView *)modifyTableView{
    
    if (!_modifyTableView)
    {
        _modifyTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.navgationBar.height+15, kScreenWidth, kScreenHeight-15-64) style:UITableViewStyleGrouped];
        _modifyTableView.backgroundColor = RGBColor(242,242,242);
    }
    return _modifyTableView;
}
- (MJChooseImageView *)chooseImageView{
    
    if (!_chooseImageView)
    {
        _chooseImageView = [[MJChooseImageView alloc] initWithFrame:self.view.bounds];
    }
    return _chooseImageView;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
